use std::{fs};
use base64::{Engine, engine};
use libaes::Cipher;

/// 程序panic后借用console.log输出报错位置
pub fn set_panic_hook() {
  // When the `console_error_panic_hook` feature is enabled, we can call the
  // `set_panic_hook` function at least once during initialization, and then
  // we will get better error messages if our code ever panics.
  //
  // For more details see
  // https://github.com/rustwasm/console_error_panic_hook#readme
  #[cfg(feature = "console_error_panic_hook")]
  console_error_panic_hook::set_once();
}

/// console.log宏封装
#[macro_export]
macro_rules! log {
  ( $( $t:tt )* ) => {
    web_sys::console::log_1(&format!( $( $t )* ).into());
  }
}

/// 写内容到文件中
pub fn write_to_file(key: &str, value: &str) {
  let line = format!("{}:{}", key, value);
  fs::write("/Users/Emiya/Documents/github/my/projectR/wasm/cache", line).unwrap();
  log!("Set value into file:{},{}", key, value);
}

/// 从文件中读内容
pub fn read_from_file(key: &str) -> String {
  let mut ret = "";
  let contents = fs::read_to_string("/Users/Emiya/Documents/github/my/projectR/wasm/cache").unwrap();
  let values: Vec<&str> = contents.lines().filter(|line| line.contains(key)).collect();
  if values.len() > 0 {
    ret = values[0].split(":").last().unwrap();
    log!("Get value from file:{}", ret);
  }
  String::from(ret)
}

// pub async fn request_url(url: &str) -> Result<HashMap<String, String>, Box<dyn Error>> {
//   let resp = reqwest::get(url)
//     .await?
//     .json::<HashMap<String, String>>()
//     .await?;
//   Ok(resp)
// }

/// aes128+base64加密，预置了key和iv
pub fn aes_encode(str: &str) -> String {
  let my_key = b"1ikl3j7rlg1z2vcl"; // key is 16 bytes, i.e. 128-bit
  let plaintext = str.as_bytes();
  let iv = b"4uu8w55a5p4nolp4";
  // Create a new 128-bit cipher
  let cipher = Cipher::new_128(my_key);
  let encrypted = cipher.cbc_encrypt(iv, plaintext);
  log!("console.log from rust! encode Vec<u8> is : {:?}", encrypted);
  engine::general_purpose::STANDARD.encode(encrypted)
}

/// aes128+base64解密，预置了key和iv
pub fn aes_decode(str: &str) -> String {
  let str = engine::general_purpose::STANDARD.decode(str).unwrap();
  let my_key = b"1ikl3j7rlg1z2vcl"; // key is 16 bytes, i.e. 128-bit
  let iv = b"4uu8w55a5p4nolp4";
  // Create a new 128-bit cipher
  let cipher = Cipher::new_128(my_key);
  let decrypted = cipher.cbc_decrypt(iv, &str[..]);
  String::from_utf8(decrypted).unwrap()
}

/// heic图片转base64
pub fn heic2jpg(buf: Vec<u8>) -> Vec<u8> {
  let data = read_avif(&mut buf).unwrap();
  
  av1_decode(&data.primary_item);
  if let Some(alpha) = &data.alpha_item {
      av1_decode(alpha);
  }
  if data.premultiplied_alpha {
      // after decoding, remember to divide R,G,B values by A
  }
  vec![]
}
